package com.example.asus.diary_demo;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.example.asus.diary_demo.RecyclerView.RecyclerViewAdapter;
import org.litepal.crud.DataSupport;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class LifeDiary extends AppCompatActivity {
    private int status;//读写标志位
    private int diaryID;
    private int id;
    private Diary diary;
    private String diaryTITLE;
    private String diaryBODY;
    private String switchButton;
    private RecyclerViewAdapter adapter;
    private RecyclerView recyclerView;

    public static final int INSERT=1;//写标志
    public static final int EDIT=2;//读标志

    private List<Diary> diaryTextList=new ArrayList<>();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_list);
//        try {
//            //屏蔽真机的Menu来显示邮编overflow button按钮
//            ViewConfiguration mconfig = ViewConfiguration.get(this);
//            Field menuKeyField;
//            menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
//            if (menuKeyField != null) {
//                menuKeyField.setAccessible(true);
//                menuKeyField.setBoolean(mconfig, false);
//            }
//        } catch (NoSuchFieldException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
//        }

        switchButton="layout1";
        diaryTextList= DataSupport.order("date desc").find(Diary.class);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
//        StaggeredGridLayoutManager layoutManager=new
//                StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
//        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerViewAdapter(diaryTextList);
        recyclerView.setAdapter(adapter);

        registerForContextMenu(recyclerView);

        //进入主页面是读取上一次关闭时的布局状态，并设置为该状态
        switchButton = load();
        if (switchButton.equals("Layout1")) {
            StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(manager);
            recyclerView.setAdapter(adapter);
            switchButton = "Layout2";
        } else {
            StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(manager);
            recyclerView.setAdapter(adapter);
            switchButton = "Layout1";
        }


        adapter.setOnMyItemClickListener(new RecyclerViewAdapter.OnMyItemClickListener(){
            @Override
            public void myClick(View v, int position) {
                Diary diary=diaryTextList.get(position);
                status=EDIT;
                Intent intent=new Intent(LifeDiary.this,DiaryEditor.class);
                intent.putExtra("Status",status);
                intent.putExtra("Content",diary);
                startActivity(intent);
                finish();
            }

            @Override
            public boolean mLongClick(View v, int position) {
                diary=diaryTextList.get(position);
                diaryID=diary.getId();
                diaryTITLE=diary.getTitle();
                id=position;
                return false;
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.action_bar,menu);
        return true;
    }
    //添加选择菜单的选择事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.MENU_ITEM_CREATE:
                Intent intent=new Intent(LifeDiary.this,DiaryEditor.class);
                status=INSERT;
                intent.putExtra("Status",status);
                startActivity(intent);
                finish();
                break;
            case R.id.MENU_ITEM_SWITCH: //切换布局
                if (switchButton.equals("Layout1")){
                    StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL);
                    recyclerView.setLayoutManager(manager);
                    recyclerView.setAdapter(adapter);
                    switchButton="Layout2";
                    save("Layout1");//保存当前布局状态
                }else {
                    StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
                    recyclerView.setLayoutManager(manager);
                    recyclerView.setAdapter(adapter);
                    switchButton="Layout1";
                    save("Layout2");//保存当前布局状态
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0,1,1,"删除");
        menu.add(0,2,2,"分享");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case 1:
                AlertDialog.Builder dialog=new AlertDialog.Builder(this);
                dialog.setTitle("删除日记");
                dialog.setMessage("确定删除日记 \""+diaryTITLE+"\"");
                dialog.setCancelable(false);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteDiary();

                        //刷新List
                        diaryTextList.remove(id);
                        adapter.notifyItemRemoved(id);
                        adapter.notifyItemRangeRemoved(0,diaryTextList.size());

                        Toast.makeText(LifeDiary.this, R.string.diary_delete_success,
                                Toast.LENGTH_LONG).show();
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case 2:
                Intent intent=new Intent(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_TEXT,diary.getTitle().toString()+" "+diary.getBody().toString());
                intent.setType("text/plain");
                startActivity(Intent.createChooser(intent,"分享到..."));
                break;
        }
        return super.onContextItemSelected(item);
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        status=0;
//        diaryTextList.clear();
//        List<Diary> newList= DataSupport.order("date desc").find(Diary.class);
//        diaryTextList.addAll(newList);
//
//        adapter=new RecyclerViewAdapter(diaryTextList);
//        recyclerView.setAdapter(adapter);
//    }

    public void deleteDiary(){
        DataSupport.deleteAll(Diary.class,"id=?",String.valueOf(diaryID));
    }

    //将text写入文件
    public void save(String LayoutStatus){
        FileOutputStream out=null;
        BufferedWriter writer=null;
        try{
            out=openFileOutput("switch", Context.MODE_PRIVATE);
            writer=new BufferedWriter(new OutputStreamWriter(out));
            writer.write(LayoutStatus);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(writer!=null) {
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public String load(){
        FileInputStream fileInputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try
        {
            fileInputStream = openFileInput("switch");
            bufferedReader = new BufferedReader(
                    new InputStreamReader(fileInputStream));
            String result = "";
            while ((result = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(result);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bufferedReader != null)
            {
                try
                {
                    bufferedReader.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode,resultCode,intent);
    }
}